package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOPTYPE;
import static com.hmdp.utils.RedisConstants.CACHE_SHOP_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryList() {
        //1.从redis中查询缓存
        String key =CACHE_SHOPTYPE ;
        String shopTypeJson = stringRedisTemplate.opsForValue().get(key);
        //2.判断缓存是否命中
        if (StrUtil.isNotBlank(shopTypeJson)) {
            //3.命中，直接返回
            List<ShopType> shopTypes = JSONUtil.toList(shopTypeJson, ShopType.class);
            return Result.ok(shopTypes);

        }
        //4.未命中
        //5.查询数据库
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //6.判断商铺类型缓存是否存在
        //7.不存在，返回404，结束
        if (typeList == null) {
            return Result.fail("无此类数据");
        }
        //8.存在，将商铺类型数据写入redis
        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(typeList));

        //9.返回商铺类型信息，结束

        return Result.ok(typeList);

    }
}
